package com.liuguang.common.utils;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WebUtil
 * @Description：
 * @Author: wanghr
 * Date: 5:39 PM 2020/10/12
 * Version: 1.0
 */
public class WebUtil {
    private static final Logger logger = LoggerFactory.getLogger(WebUtil.class);

    public static void responseFriendly(HttpServletResponse response, Integer code, String msg) throws IOException {
        //传入参数都不能为空
        Assert.notNull(response);
        Assert.notNull(code);
        Assert.notNull(msg);
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("data", msg);
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    public static String getIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取remoteAddr：{}", remoteAddr);
        //可能存在 请求被nginx转发的情况，需要在请求头中获取，请求头的名字，根据nginx中定义的获取
        //String header = request.getHeader(realRemoteAddr);
        return remoteAddr;
    }
}
